﻿using LitJson;
using LNet;
using OestsCommon.Model;
using OestsDataBase;
using OestsServer.Net;
using System.Collections.Generic;
using System.Linq;

namespace OestsServer.Handlers.OESPHandlers
{
    /// <summary>
    /// 处理请求数据
    /// </summary>
    public class AddStudentClassHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey
        {
            get
            {
                return PacketKey.AddStudentClass;
            }
        }
        public override void Execute(OESPClientChannel client, Request packet)
        {
            base.Execute(client, packet);

            List<StudentClass> list = JsonMapper.ToObject<List<StudentClass>>(packet.DataStr);
            List<StudentClass> back = list.Where(sc =>
            {
                return StudentClassDAL.AddStudentClass(sc) > 0;
            }
            ).ToList();
            ResponsePacket.DataObject = back;
            client.Send(ResponsePacket);
        }
    }

    public class ModifyStudentClassHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey
        {
            get
            {
                return PacketKey.ModifyStudentClass;
            }
        }
        public override void Execute(OESPClientChannel client, Request packet)
        {
            base.Execute(client, packet);

            List<StudentClass> list = JsonMapper.ToObject<List<StudentClass>>(packet.DataStr);
            //由于学生和班级是多对多的关系，所以，每次修改要把之前的学生删除掉，然后添加
            HashSet<int> set = new HashSet<int>();//避免重复标识
            foreach (var sc in list)
            {
                set.Add(sc.StudentId);
                //StudentClassDAL.DeleteByStdID(sc.StudentId);
            }
            StudentClassDAL.DeleteByStdIds(set);//删除所有学生的班级信息
            
            //添加班级信息
            StudentClassDAL.AddStudentClass(list);
            ResponsePacket.DataObject = list;
            client.Send(ResponsePacket);
        }
    }

    public class DeleteStudentClassHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey
        {
            get
            {
                return PacketKey.DeleteStudentClass;
            }
        }
        public override void Execute(OESPClientChannel client, Request packet)
        {
            base.Execute(client, packet);

            List<int> list = JsonMapper.ToObject<List<int>>(packet.DataStr);
            StudentClassDAL.DeleteByStdIds(list);
            //List<int> back = list.Where(id => ).ToList();
            ResponsePacket.DataObject = list;
            client.Send(ResponsePacket);
        }
    }

}
